/**
 * 
 */
package com.softcits.upload.demo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

/**
 * @author dac
 *
 */
@WebServlet(urlPatterns= {"/upload"})
public class FileUploadServlet extends HttpServlet {

    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        // Create a factory for disk-based file items
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //
        factory.setSizeThreshold(1024000);
        File root = new File("./files");
        if(!root.exists()) {
            root.mkdirs();
        }
        factory.setRepository(root);
        ServletFileUpload upload = new ServletFileUpload(factory);
//        upload.setFileSizeMax(fileSizeMax);
//        upload.setSizeMax(sizeMax);
        upload.setHeaderEncoding("utf-8");
        boolean isFileUpload = ServletFileUpload.isMultipartContent(req);
        if(!isFileUpload) {
            out.println("The current request is not file upload request.");
            return;
        }
        
        ProgressListener progressListener = new ProgressListener() {
            private long megaBytes = -1;
            private int count = 1;
            private int idx = 1;
            @Override
            public void update(long pBytesRead, long pContentLength, int pItems) {
                if(pItems == 0) {
                    return;
                }
                idx = pItems;
                
                if(idx != pItems) {
                    count = 1;
                    megaBytes = -1;
                }
                long mBytes = pContentLength / 100;
                megaBytes = mBytes * count;
                if(pBytesRead < this.megaBytes) {
                    return;
                }
                
                
                
                System.out.println("We are currently reading item " + pItems);
                if(pContentLength == -1) {
                    System.out.println("So far, 100%"  + pBytesRead + " bytes have been read.");
                } else {
                    if(count < 100 && pBytesRead == pContentLength) {
                        count = 100;
                        System.out.println("So far, " + count + "% " + pBytesRead + " of " + pContentLength + " bytes have been read.");
                        return;
                    } else {
                        if(count > 100) {
                            count = 100;
                        }
                        System.out.println("So far, " + count + "% " + pBytesRead + " of " + pContentLength + " bytes have been read.");
                    }
                    
                }
                
                count ++;
                
            }
        };
        upload.setProgressListener(progressListener);
        String key = req.getParameter("key");
        try {
            List<FileItem> fis = upload.parseRequest(req);
            
            for(FileItem fi: fis) {
                if(fi.isFormField()) {
                    // TODO
                    //out.println(fi.getFieldName() + ": " + fi.getString("utf-8"));
                } else {
                    InputStream is = fi.getInputStream();
                    String fileName = fi.getName();
                    File dest = new File(root, fileName);
                    FileOutputStream fos = new FileOutputStream(dest);
                    IOUtils.copy(is, fos);
                    IOUtils.closeQuietly(fos);
                    out.println("File - " + fileName + " Uploaded successfully.<br/>");
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
    }
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.getWriter().print("Hello World");
    }
}
